
package com.imti.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imti.pojo.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@ToString
public class PageBean<T> {

	// 每页显示条数
	private Long pageSize = 10L;
	// 总条数
	private Long totalPage = 0L;
	// 当前页码
	private Long pageNum = 1L;
	// 总页数
	private Long total = 0L;

	// 存储返回的集合对象
	private List<T> resultList;

	/**
	 * 将SpringData分页后的list转为分页信息
	 */
	public static <T> PageBean<T> restPage(IPage<T> pageInfo) {
		PageBean<T> result = new PageBean<T>();
		result.setTotal(pageInfo.getTotal());
		result.setPageNum(pageInfo.getCurrent());
		result.setPageSize(pageInfo.getSize());
		result.setTotalPage(pageInfo.getPages());
		result.setResultList(pageInfo.getRecords());
		return result;
	}

	/**
	 * 将自定义sql查询结果的list转为分页信息
	 */
	public static <T> PageBean<T> restPage(IPage<User> page, List<T> list) {

		PageBean<T> result = new PageBean<T>();
		result.setResultList(list);
		result.setTotal(null != list ? list.stream().count() : 0);
		result.setPageNum(null != page ? page.getCurrent() : result.pageNum);
		result.setPageSize(null != page ? page.getSize() : result.pageSize);
		result.setTotalPage(null != page ? page.getPages() : result.totalPage);
		return result;
	}

	public static void main(String[] args) {
		IPage<User> page = new Page<>();
		List<User> list = new ArrayList<>();
		PageBean<User> userPageBean = restPage(page, list);
		System.out.println(userPageBean);
	}
}
